package com.atguigu.serviceedu.service.impl;

import com.atguigu.commonutils.R;
import com.atguigu.servicebase.handler.GuliException;
import com.atguigu.serviceedu.entity.EduVideo;
import com.atguigu.serviceedu.feign.VideoFeignService;
import com.atguigu.serviceedu.mapper.EduVideoMapper;
import com.atguigu.serviceedu.service.EduVideoService;
import com.atguigu.serviceedu.vo.EduVideoInform;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author wyj
 * @since 2021-12-19
 */
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {
    @Autowired
    VideoFeignService videoFeignService;

    @Override
    public boolean getCountByChapterId(String id) {
        QueryWrapper<EduVideo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("chapter_id", id);
        Integer count = baseMapper.selectCount(queryWrapper);
        return null != count && count > 0;
    }

    @Override
    public boolean removeVideoById(String id) {
        EduVideo eduVideo = this.getById(id);
        if(!StringUtils.isEmpty(eduVideo.getVideoSourceId())){
            R code = videoFeignService.removeVideo(eduVideo.getVideoSourceId());
            if (code.getCode() == 20001){
                throw new GuliException(20001,"调用远程服务失败,启动熔断器的方法");
            }
        }
        boolean result = this.removeById(id);
        return result;
    }

    @Override
    public void removeVideoByCourseId(String id) {
        //根据课程id查询出所有的视频id
        List<EduVideo> eduVideos = this.list(new QueryWrapper<EduVideo>().eq("course_id", id));
        List<String> sourceIds = eduVideos.stream().map(EduVideo::getVideoSourceId).filter(item->{
            return !StringUtils.isEmpty(item);
        }).collect(Collectors.toList());
        //调用远程服务接口删除阿里云上对应的视频
        if (sourceIds.size() > 0){
            videoFeignService.removeVideoByIds(sourceIds);
        }

        //删除对应的所有小节
        this.remove(new QueryWrapper<EduVideo>().eq("course_id",id));
    }

    @Override
    public EduVideoInform getEduVideoInformById(String id) {
        EduVideo eduVideo = this.getById(id);
        EduVideoInform eduVideoInform = new EduVideoInform();
        BeanUtils.copyProperties(eduVideo,eduVideoInform);
        //根据小节的查询视频列表
        eduVideoInform.setUploadVidoName(videoFeignService.getUploadVideoTitle(eduVideo.getVideoSourceId()));
        return eduVideoInform;
    }
}
